package com.neusoft.neuiotms.dcom.repository.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcom.model.MaintainRule;
import com.neusoft.neuiotms.dcom.model.QMaintainRule;
import com.neusoft.neuiotms.dcom.repository.CustomizedMaintainRuleRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedMaintainRuleRepositoryImpl extends AbstractRepository
        implements CustomizedMaintainRuleRepository {

    @Override
    public List<MaintainRule> search(final Searchable searchable) {
        final QMaintainRule qMaintainRule = QMaintainRule.maintainRule;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<MaintainRule> query = this.query().selectFrom(qMaintainRule);
        query.where(where);
        return query.fetch();
    }

    @Override
    public Page<MaintainRule> search(final Pageable pageable, final Searchable searchable) {
        final QMaintainRule qMaintainRule = QMaintainRule.maintainRule;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<MaintainRule> query = this.query().selectFrom(qMaintainRule);
        query.where(where);
        return super.search(query, pageable);
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QMaintainRule qMaintainRule = QMaintainRule.maintainRule;

        if (!StringUtils.isEmpty(searchable.getStrValue("name"))) {
            where.and(super.containsStr(qMaintainRule.name, searchable, "name"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("modelCode"))) {
            where.and(super.containsStr(qMaintainRule.modelCode, searchable, "modelCode"));
        }

        return where;
    }

    @Override
    protected Class<?> getModelClass() {
        return MaintainRule.class;
    }

}
